package com.wwz.leetcode;

import org.junit.Test;

/**
 * 买卖股票的最佳时机
 */
public class LeetCode121 {


    @Test
    public void test() {
        System.out.println(maxProfit2(new int[]{7, 1, 5, 3, 6, 4}));

    }

    // 超时了
    public int maxProfit(int[] prices) {
        int earn = 0;
        int temp = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                temp = prices[j] - prices[i];
                if (temp > 0 && temp > earn) {
                    earn = temp;
                }
            }
        }
        return earn;
    }

    public int maxProfit2(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

}
